package Demo1;
import java.sql.*;
import com.alibaba.fastjson2.JSON;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@WebServlet({"/test01"})
public class JsonTest extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
         resp.setContentType("text/html;charset=UTF-8");
         PrintWriter out = resp.getWriter();

         //从数据库查询数据
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        // 获取连接
        connection =DBUtil.getConnection();
        // 执行sql语句
        String sql = "select id,name,age,addr from t_student";
            // 从数据库中查询
        // new一个集合,用于存储Student对象
        List<Student> studentList = new ArrayList<>();
            try {
                preparedStatement = connection.prepareStatement(sql);
                resultSet = preparedStatement.executeQuery();
                while(resultSet.next()){
                    String name = resultSet.getString("name");
                    int id = resultSet.getInt("id");
                    int age = resultSet.getInt("age");
                    String addr = resultSet.getString("addr");
                    Student student = new Student(id,name,age,addr);
                    studentList.add(student);
                }
                // 最终完成之后,将整个List集合转化为json字符串返回给前端.
                String jsonStr  = JSON.toJSONString(studentList);
                out.print(jsonStr);
            } catch (SQLException ex) {
                ex.printStackTrace();
            }
            // 最后一步,关闭资源
            finally {
                if (resultSet != null) {
                    try {
                        resultSet.close();
                    } catch (SQLException e) {
                        throw new RuntimeException(e);
                    }
                }
                if (preparedStatement != null) {
                    try {
                        preparedStatement.close();
                    } catch (SQLException e) {
                        throw new RuntimeException(e);
                    }
                }
                if (connection != null) {
                    if (connection != null) {
                        try {
                            connection.close();
                        } catch (SQLException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
    }
}
